<template>
  <div class="autoBox" @click="isShow=false" :style="{height:$height-159+'px',overflow:'hidden'}">
    <header>
      <span class="auto_title">邮件自动化</span>
      <a href="javascript:void(0)">
        <b class="search-roll">
          <input type="text" placeholder="输入模板名称查找" class="search" v-model="keyWord"
                 @keyup.enter="handleCurrentChange(1)">
          <i class="el-icon-search" @click="handleCurrentChange(1)"></i>
        </b>
        <el-button size="mini" class="new-btn" type="primary" @click="enterDetail(-1,'/automation/mailAutomation/add')" id="addEmailRule">+创建邮件自动规则
        </el-button>
      </a>
    </header>
    <div class="common-list">
      <table class="temp-table">
        <thead>
        <tr>
          <th style="width:1px;padding: 3px 7px"></th>
          <th style="width: 198px">规则名称</th>
          <th>创建时间</th>
          <th style="width: 300px">有效时间</th>
          <th>是否启用</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody :style="{minHeight:$height-239+'px'}">
        <div v-for="item,index in tableData" :key="index">
          <tr>
            <td style="width:1px;padding: 3px 7px" @click="toggle($event)"><i class="el-icon-arrow-down"></i></td>
            <td class="more" style="width: 198px;" :title="item.name" @click="toggle($event)">{{item.name}}</td>
            <td @click="toggle($event)">{{item.createTime}}</td>
            <td style="width: 300px" @click="toggle($event)">
              {{item.startDate}} <b>至</b> {{item.endDate}}
            </td>
            <td>
              <el-switch v-if="filterOutDate(item.endDate,item.isMine)"
                         @change="(value) => changeUse(item,item.id,value)" :title="item.isEnable?'停用':'启用'"
                         v-model="item.isEnable" style="width:30px" :disabled="!item.isMine">
              </el-switch>
              <el-switch v-else v-model="item.isEnable" style="width:30px" disabled="disabled">
              </el-switch>
            </td>
            <td @click="toggle($event)">
              <span class="icon-copy iconBtn" title="复制邮件模板" @click.stop="copy(item)"></span>
              <!-- 启动一次 即废除-->
              <span class="icon-bianji iconBtn" title="编辑" @click.stop="enterDetail(item.id,'/automation/mailAutomation/edit')"
                    v-show="item.isMine&&!item.hasRun"></span>
              <span v-show="item.hasRun" class="icon-bianji iconBtn" title="规则启用过一次之后，无法修改规则" style="color: #c0c4cc"
                    @click.stop="()=>{}"></span>
              <span class="icon-delete_icon iconBtn" title="删除" @click.stop="remove(item)"
                    v-show="item.isMine"></span>
            </td>
          </tr>
          <div class="detail" style="display: none">
            <table>
              <thead>
              <tr>
                <th style="width:1px;padding: 3px 7px"></th>
                <th style="width: 198px">分组名称</th>
                <th>触发条件 => 执行事件 <span style="margin-left: 450px;">执行次数</span></th>
              </tr>
              </thead>
              <tbody>
              <tr title="点击展开规则详情">
                <td style="width:1px;padding: 3px 7px"></td>
                <td style="width: 183px">{{item.cutGroupName}}</td>
                <td>
                  <ul>
                    <li v-for="itemSon,index in item.subrules" :key="index">
                      <div v-if="itemSon.type==0">
                        <a href="javascript:void(0)">
                          <p><img class="icon" src="../../../../public/img/icon/auto-man.png" alt=""> 客户被建档</p>
                          <p>
                            <img class="icon" src="../../../../public/img/icon/auto-next.png" alt=""> 且初始<span>分组</span>为
                            【<span>{{itemSon.sourceGroupName}}</span>】
                          </p>
                          <p>
                            <img class="icon" src="../../../../public/img/icon/auto-email.png" alt="">
                            系统使用<span>{{itemSon.sendEmail}}</span>向客户发送邮件【<span>{{itemSon.sendTemplateName}}</span>】
                          </p>
                        </a>
                        <span class="open-time">{{itemSon.execCount}}次</span>
                      </div>
                      <div v-else-if="itemSon.type==1">
                        <a href="javascript:void(0)">
                          <p>
                            <img class="icon" src="../../../../public/img/icon/auto-man.png" alt="">
                            客户打开邮件【{{itemSon.openTemplateName}}】
                          </p>
                          <p>
                            <img class="icon" src="../../../../public/img/icon/auto-email.png" alt="">
                            系统使用<span>{{itemSon.sendEmail}}</span>向客户发送邮件【<span>{{itemSon.sendTemplateName}}</span>】
                          </p>
                        </a>
                        <span class="open-time">{{itemSon.execCount}}次</span>
                      </div>
                      <div v-else-if="itemSon.type==2&&itemSon.changeGroupId">
                        <a href="javascript:void(0)">
                          <p>
                            <img class="icon" src="../../../../public/img/icon/auto-man.png" alt="">
                            客户打开邮件【<span>{{itemSon.openTemplateName}}</span>】
                          </p>
                          <p>
                            <img class="icon" src="../../../../public/img/icon/auto-next.png" alt=""> 系统将此客户分组转到【<span>{{itemSon.changeGroupName}}</span>】
                          </p>
                        </a>
                        <span class="open-time">{{itemSon.execCount}}次</span>
                      </div>
                    </li>
                  </ul>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </div>
        <tr v-show="isEnd" class="empty-img" style="background-color: #fff;border-bottom: 0">
          <td colspan="8" style="background-color: #fff">
            <img src="../../../../public/img/empty.png" alt="">
          </td>
        </tr>
        </tbody>
      </table>
      <el-pagination class="fixed"
                     background align="right"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="nowPage"
                     :page-size="nowSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <VueTour ref="vueTour" :steps="steps" prev="/automation/template/email" type="0"
             path="/automation/mailAutomation/add?type=2"></VueTour>
  </div>
</template>

<script>
    import {getList, changeShare, changeUse, deleteTemplate, copyRule, getNextMan} from "@/api/mailAutomation"
    import VueTour from '@/components/automation/VueRour'
    import {mapState} from 'vuex'

    export default {
        name: "index",
        components: {VueTour},
        data() {
            return {
                tableData: [],
                nowPage: 1,
                nowSize: 20,
                total: 0,
                state: false,
                keyWord: '',//搜索
                account: [],
                checkList: [],
                createNames: '',
                isShow: false,
                checked: false,
                activeName: 0,
                steps: [
                    {
                        target: '#addEmailRule',
                        content: '【邮件自动化规则创建】<br>第三步，点击添加邮件自动化规则',
                    },
                ],
                isEnd: false
            }
        },
        computed: {
            ...mapState(['common'])
        },
        created() {
            this.nowPage = this.common.commonPage;
            this.nowSize = this.common.commonPageSize;
        },
        mounted() {
            if (this.common.isFirstEmail) {
                this.$nextTick(() => {
                    this.$refs.vueTour.init();//初始化
                })
            }
            this.getList()
            this.getNextMan();
        },
        watch: {
            isShow: function (val, old) {
                if (!val) {
                    if (this.checkList.length > 0) {
                        if (this.checked) {//全选
                            this.createNames = '';
                        } else {
                            this.createNames = this.checkList.join(',');
                        }
                        this.nowPage = 1;
                        this.isShow = false;
                        this.getList();
                    }
                } else {
                    this.createNames = '';
                    this.checked = false;
                    this.checkList = [];
                }
            }
        },
        methods: {
            //判断当前是否过期
            filterOutDate(time, isMine) {
                if (isMine) {//我的
                    return new Date(time).getTime() > new Date().getTime(); //大于，  过期  true
                } else {//别人的
                    return false
                }
            },
            toggle(event) {
                let that = event.currentTarget.parentNode;
                let ele = that.nextElementSibling;
                let eleChild = that.firstElementChild.firstElementChild;
                eleChild.className = eleChild.className == 'el-icon-arrow-down' ? 'el-icon-arrow-up' : 'el-icon-arrow-down';
                let state = ele.style.display;
                ele.setAttribute('style', `display:${state == 'none' ? 'block' : 'none'};`);
            },
            //复制
            copy(row) {
                this.$router.push({
                    path: `/automation/mailAutomation/edit/${row.id}`,
                    query: {
                        type: 1,
                        isMine: row.isMine
                    }
                })
            },
            remove(row) { // 删除模板
                //判断是否执行结束
                if (row.isEnable) {
                    this.$message({
                        type: "success",
                        message: '请先停用该规则,才可以删除'
                    });
                    return;
                }
                this.$confirm(`<div style="margin: 20px 10px;"><p style="line-height: 30px;font-size: 15px;color: #333">确认删除该邮件规则吗?</p></div>`, '邮件自动化', {
                    dangerouslyUseHTMLString: true,
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取 消',
                }).then(() => {
                    deleteTemplate(row.id).then(res => {
                        if (res.data.success) {
                            this.dealEnd(res)
                        }
                    })
                }).catch(() => {
                })
            },
            handleChange(val) {
                if (val) {
                    this.checkList = this.account;
                } else {
                    this.checkList = []
                }
            },
            handle(val) {
                this.checked = val.length == this.account.length
            },
            getNextMan() {
                getNextMan().then(res => {
                    if (res.data.success) {
                        this.account = res.data.data
                    }
                })
            },
            //进入新增 - 编辑页面
            enterDetail(id,path) {
                this.$store.commit('SET_COMMONPAGE', {page: this.nowPage, pageSize: this.nowSize});
                this.$router.push({
                    path:id==-1?path: `${path}/${id}`,
                    query: {
                        type: id == -1 ? id : 2,
                        isMine: true
                    }
                })
            },
            changeShare(row, id, state) {
                row.isShare = !state;
                this.$confirm(`<div style="margin: 20px 10px;"><p style="line-height: 30px;font-size: 15px;color: #333">${state ? '' : '取消'}共享该邮件规则?</p></div>`, '邮件自动化', {
                    dangerouslyUseHTMLString: true,
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取 消',
                }).then(() => {
                    changeShare(id, state).then(res => {
                        if (res.data.success) {
                            this.dealEnd(res)
                        }
                    })
                }).catch(() => {
                })
            },
            changeUse(row, id, state) {
                row.isEnable = !state;
                this.$confirm(`<div style="margin: 20px 10px;"><p style="line-height: 30px;font-size: 15px;color: #333">${state ? '启用' : '停用'}该邮件规则?</p></div>`, '邮件自动化', {
                    dangerouslyUseHTMLString: true,
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取 消',
                }).then(() => {
                    changeUse(id, state).then(res => {
                        this.dealEnd(res)
                    })
                }).catch(() => {
                })
            },
            getList() {
                getList(this.keyWord, this.createNames, this.nowPage, this.nowSize).then(res => {
                    if (res.data.success) {
                        const result = res.data.data;
                        this.tableData = result.records;
                        this.total = result.total;
                        console.log(this.tableData)
                        this.isEnd = this.total == 0;
                    }
                })
            },
            dealEnd(res) {
                if (res.data.success) {
                    this.getList();
                    this.$message({message: res.data.msg, type: 'success'});
                } else {
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                }

            },
            handleSizeChange(size) { //  条数发生改变
                this.nowSize = size
                this.$store.commit('SET_COMMONPAGE', {page: this.nowPage, pageSize: this.nowSize});
                this.getList()
            },
            handleCurrentChange(page) { //页数发生变化
                this.nowPage = page
                this.$store.commit('SET_COMMONPAGE', {page: this.nowPage, pageSize: this.nowSize});
                this.getList()
            }
        }
    }
</script>

<style lang="scss" scoped>
  .autoBox {
    .detail {
      table {
        tbody {
          tr {
            td {
              background-color: #fff;

              ul {
                li {
                  position: relative;
                  padding-left: 15px;
                  border-bottom: 1px solid #F3F3F3;

                  div {
                    display: flex;
                    align-items: center;
                    padding: 15px 0;
                    a{
                      width: 600px;
                      display: inline-block;
                    }
                    .icon {
                      width: 14px;
                    }
                  }
                }

                li:last-child {
                  border-bottom: none;
                }

              }

            }
          }
        }
      }

      .open-time {
        color: #000;
      }
    }

    i {
      color: #2A97F9;
    }

    .active {
      display: block;
      opacity: 1;
    }

    .noActive {
      display: none;
      opacity: 0;
    }

    tbody {
      overflow-y: auto;

      tr {
        color: #333;
      }
    }

    header {
      display: flex;
      justify-content: space-between;
    }

    .iconBtn {
      margin: 0 6px;
      cursor: pointer;
    }

    .pagination {
      text-align: right;
    }
  }


</style>
